<template>
  <div class="reports">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
      <el-steps :active="activeName - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleFormShop"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          :tab-position="'left'"
          v-model="activeName"
          :before-leave="beforeLeave"
          @tab-click="tabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="ruleForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="ruleForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="ruleForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="ruleForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="ruleForm.goods_cat"
                :options="options"
                :props="props"
                @change="handleChange"
                style="width:500px"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="(item,index) in this.manyData"
              :key="index"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border :label="inner" v-for="(inner,i) in item.attr_vals" :key="i"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="(item,index) in this.onlyData"
              :key="index"
            >
              <el-input v-model="item.attr_vals" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              ref="myupload"
              action="http://127.0.0.1:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :on-error="handleError"
              :headers="headersObj"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="ruleForm.goods_introduce"></quill-editor>
            <el-button type="primary" style="margin-top:15px;" @click="submitShop">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <el-dialog title="预览图片" :visible.sync="PreviewVisible" width="30%">
      <img :src="PreviewImg" style="width:100%" />
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash';
export default {
  name: "reports",
  data() {
    return {
      activeName: 0,
      manyData: [],
      onlyData: [],

      ruleForm: {
        goods_name: "",
        goods_price: "",
        goods_weight: "",
        goods_number: "",
        goods_cat: "",
        pics: [],
        goods_introduce:"",
        attrs:[]
      },
      props: {
        expandTrigger: "hover",
        label: "cat_name",
        value: "cat_id",
        children: "children",
      },
      options: [],
      rules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商商品数量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请输入商品分类", trigger: "blur" },
        ],
      },
      headersObj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      PreviewImg: null,
      PreviewVisible: false
    };
  },
  methods: {
    handleChange(value) {
      if (value.length !== 3) {
        this.ruleForm.goods_cat = [];
      }
    },
    getcategories() {
      this.$http.get("categories").then((res) => {
        //console.log(res.data.meta.status == 200);
        if (res.data.meta.status == 200) {
          this.options = res.data.data;
          console.log(this.options);
        }
      });
    },
    beforeLeave(activeName, oldActiveName) {
      //console.log(activeName);
      //console.log(oldActiveName);
      if (oldActiveName == "0" && this.ruleForm.goods_cat.length !== 3) {
        this.$message.error("请选择商品三级分类");
        return false;
      }
    },
    tabClick() {
      if (this.activeName == "1") {
        this.$http
          .get(`categories/${this.myId}/attributes`, {
            params: { sel: "many" },
          })
          .then((res) => {
            if (res.data.meta.status !== 200) {
              return this.$message.error("获取商品参数失败");
            }
            console.log(res);
            this.manyData = res.data.data;
            console.log(this.manyData);
            this.manyData.forEach((item) => {
              item.attr_vals =
                item.attr_vals.length == 0 ? [] : item.attr_vals.split(" ");
            });
          });
      } else if (this.activeName == "2") {
        this.$http
          .get(`categories/${this.myId}/attributes`, {
            params: { sel: "only" },
          })
          .then((res) => {
            if (res.data.meta.status !== 200) {
              return this.$message.error("获取商品参数失败");
            }

            this.onlyData = res.data.data;
            console.log(this.onlyData);
          });
      }
    },
    handlePreview(file) {
      //console.log(file.response.data.url)
      this.PreviewImg = file.response.data.url;
      this.PreviewVisible = true;
    },
    handleRemove(file) {
      const tmppath = file.response.data.tmp_path;
      const myindex = this.ruleForm.pics.findIndex((x) => {
        return x.pic === tmppath;
      });
      this.ruleForm.pics.splice(myindex, 1);
      console.log(this.ruleForm);
    },
    handleSuccess(res) {
      const infoimg = {
        pic: res.data.tmp_path,
      };
      this.ruleForm.pics.push(infoimg);
      console.log(this.ruleForm);
      console.log(res);
      //this.$refs.myupload.clearFiles();
    },
    handleError(res) {
      console.log(res);
    },
    submitShop() {
      this.$refs.ruleFormShop.validate(valid => {
        if(!valid){
          return this.$message.error("添加必要的商品信息")
        }
        const xinruleForm = _.cloneDeep(this.ruleForm);
        xinruleForm.goods_cat = xinruleForm.goods_cat.join(",");
        this.manyData.forEach( item => {
          const attr = {
            attr_id:item.attr_id,
            attr_value:item.attr_vals.join(" ")
          }
          this.ruleForm.attrs.push(attr);
        })
         this.onlyData.forEach( item => {
          const attr = {
            attr_id:item.attr_id,
            attr_value:item.attr_vals
          }
          this.ruleForm.attrs.push(attr);
        })  
        xinruleForm.attrs = this.ruleForm.attrs;
        console.log(xinruleForm)
        this.$http.post("goods",xinruleForm).then( res => {
          if(res.data.meta.status !== 201) {
            return this.$message.error("添加商品失败");
          }
          this.$message.success("添加商品成功");
          this.$router.push({path:'/home/goods'})
        })
      })
    }
  },
  computed: {
    myId() {
      if (this.ruleForm.goods_cat.length == 3) {
        return this.ruleForm.goods_cat[2];
      }
      return null;
    },
  },
  mounted() {
    this.getcategories();
  },
};
</script>

<style scoped>
.el-breadcrumb {
  margin-bottom: 20px;
}
.el-alert,
.el-steps {
  margin-bottom: 20px;
}
.el-checkbox {
  margin: 0 10px 8px 0 !important;
}
>>> .ql-container{
  min-height:500px;
}
</style>
